﻿using IPTools.Core;
using Lmg.Model;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using NLog;
using System;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace Lmg.WebApi
{
    /// <summary>
    /// 全局异常处理中间件
    /// 调用 app.UseMiddlewareGlobalExceptionMiddleware>();
    /// </summary>
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate next;

        static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        public GlobalExceptionMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            NLog.LogLevel logLevel = NLog.LogLevel.Info;
            int code = (int)ResultCode.GLOBAL_ERROR;
            string msg;
            string error = string.Empty;
            //自定义异常
            if (ex is CustomException customException)
            {
                code = customException.Code;
                msg = customException.Message;
                error = customException.LogMsg;
            }
            else if (ex is ArgumentException)//参数异常
            {
                code = (int)ResultCode.PARAM_ERROR;
                msg = ex.Message;
            }
            else
            {
                msg = "服务器好像出了点问题，请联系系统管理员...";
                error = $"{ex.Message}";
                logLevel = NLog.LogLevel.Error;
                context.Response.StatusCode = 500;
            }
            var options = new JsonSerializerOptions
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true
            };

            ApiResult apiResult = new(code, msg);
            string responseResult = JsonSerializer.Serialize(apiResult, options).ToLower();
            string ip = HttpContextExtension.GetClientUserIp(context);
            var ip_info = IpTool.Search(ip);

            sys_oper_log sysOperLog = new()
            {
                status = 0,
                oper_name = HttpContextExtension.GetName(context),
                oper_ip = ip,
                oper_url = HttpContextExtension.GetRequestUrl(context),
                request_method = context.Request.Method,
                json_result = responseResult,
                error_msg = string.IsNullOrEmpty(error) ? msg : error,

                oper_location = ip_info.Province + " " + ip_info.City,
                method = "",
                oper_time = DateTime.Now,
                oper_param = HttpContextExtension.GetRequestValue(context, context.Request.Method)
            };

            var endpoint = GetEndpoint(context);
            if (endpoint != null)
            {
                var logAttribute = endpoint.Metadata.GetMetadata<LogAttribute>();
                if (logAttribute != null)
                {
                    sysOperLog.business_type = (int)logAttribute.BusinessType;
                    sysOperLog.title = logAttribute?.Title;
                    sysOperLog.oper_param = logAttribute.IsSaveRequestData ? sysOperLog.oper_param : "";
                    sysOperLog.json_result = logAttribute.IsSaveResponseData ? sysOperLog.json_result : "";
                }
            }
            LogEventInfo ei = new(logLevel, "GlobalExceptionMiddleware", error)
            {
                Exception = ex,
                Message = error
            };
            ei.Properties["status"] = 1;//走正常返回都是通过走GlobalExceptionFilter不通过
            ei.Properties["jsonResult"] = responseResult;
            ei.Properties["requestParam"] = sysOperLog.oper_param;
            ei.Properties["user"] = sysOperLog.oper_name;

            Logger.Log(ei);
            context.Response.ContentType = "text/json;charset=utf-8";
            await context.Response.WriteAsync(responseResult, System.Text.Encoding.UTF8);

            string errorMsg = $"> 操作人：{sysOperLog.oper_name}" +
                $"\n> 操作地区：{sysOperLog.oper_ip}({sysOperLog.oper_location})" +
                $"\n> 操作模块：{sysOperLog.title}" +
                $"\n> 操作地址：{sysOperLog.oper_url}" +
                $"\n> 错误信息：{msg}\n\n> {error}";

            WxNoticeHelper.SendMsg("系统出错", errorMsg, "", WxNoticeHelper.MsgType.markdown);
            //SysOperLogService.InsertOperlog(sysOperLog);
        }

        public static Endpoint GetEndpoint(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            return context.Features.Get<IEndpointFeature>()?.Endpoint;
        }
    }
}
